const util = require('../../utils/util.js')
//todo  复杂度：1.灵活配置表单反显（了解需求，设计样式）  2.表单双向绑定（todo） 3.表单特殊校验编写
Page({
  data: {
    formData: {

    },
    configList: [{
        tempType: 'upload',
        label: '图片',
        labelDetail: '图片上传',
        keyName: 'value11',
        type: 'image',
        // value:[],
        value: [{
          "tempFilePath": "http://tmp/cDEiUWcNAtLJ82985e40281751912e762e280b2b3438.png",
          "size": 2315,
          "fileType": "image",
          "type": "image",
          "url": "http://tmp/cDEiUWcNAtLJ82985e40281751912e762e280b2b3438.png",
          "thumb": "http://tmp/cDEiUWcNAtLJ82985e40281751912e762e280b2b3438.png"
        }], //文件上传类型属性：文件存储
        valid: false
      },
      {
        tempType: 'upload',
        label: '视频',
        labelDetail: '视频上传',
        keyName: 'value10',
        type: 'video',
        // value:[],
        value: [{
          "size": 14849690,
          "duration": 13.334,
          "width": 512,
          "height": 512,
          "type": "video",
          "url": "http://tmp/W1jpT5grN6lhaa638caab161ec721ed7dfa26d89b5d3.mp4",
          "thumb": "http://tmp/AOlqNn52ctDf4c395a1a890f4c62f6d2d3d4cc0882e9.jpg"
        }],
        valid: false
      },
      {
        tempType: 'signature',
        label: '签名',
        labelDetail: '用户签名',
        keyName: 'value9',
        valid: false,
        value: "http://tmp/UGfHqUA6nyo3a93146ed420e75e6118287f51e1584a3.png",
      }, {
        tempType: 'address',
        label: '地址',
        labelDetail: '请选择当前位置',
        keyName: 'value8',
        valid: false,
        // value: {
        //   cascader: null,
        //   detail: null
        // }
        value: {
          cascader: ['北京市', '北京市', '东城区', '东华门街道'],
          detail: '11'
        }
      }, {
        tempType: 'location',
        label: '定位',
        labelDetail: '获取您的当定位置',
        keyName: 'value7',
        valid: false,
        value: [104.04311, 30.64242]
      }, {
        tempType: 'inspect',
        label: '日常巡检',
        labelDetail: '根据以下要求进行检查，符合点击是，不符合点击否',
        keyName: 'value6',
        valid: false,
        value: [ //表格类型属性：可变数组枚举
          {
            id: 'value6_1', //唯一标识
            label: '无火灾隐患', //row label
            // value: null //row value
            value: true //row value
          },
          {
            id: 'value6_2',
            label: '无设备异常',
            // value: null
            value: false
          },
        ]
      }, {
        tempType: 'input', //template类型
        label: '电话', //label
        labelDetail: '下方填写您的手机号', //字段说明
        keyName: 'value1', //后端属性名
        placeholder: '请输入', //hint
        type: 'text', //input type: text、number 
        valid: false, //是否必填,
        value: '15181127693', //默认值/简单值反显绑定
        regex: '^\\d{11}$' //部分必填的特殊校验
      }, {
        tempType: 'textarea',
        label: '备注',
        labelDetail: '下方填写备注信息',
        keyName: 'value2',
        placeholder: '请输入',
        valid: false,
        maxlength: 200, //输入类型属性：最大输入长度
        value:'我是备注'
      }, {
        tempType: 'radio',
        label: '性别',
        labelDetail: '请选择性别',
        keyName: 'value3',
        option: [{ //选择类型属性：数组枚举
          label: '男',
          value: 'man'
        }, {
          label: '女',
          value: 'woman'
        }],
        valid: false,
        value:'woman'
      },
      {
        tempType: 'table',
        label: '家庭成员',
        labelDetail: '请输入家庭成员',
        keyName: 'value4',
        valid: false,
        value: [ //表格类型属性：可变数组枚举
          {
            id: 'value4_1', //唯一标识
            label: '父亲', //row label
            value: 'daddy' //row value
          },
          {
            id: 'value4_2',
            label: '母亲',
            value: 'mommy'
          },
        ]
      },
      {
        tempType: 'checkbox',
        label: '爱好',
        labelDetail: '请选择爱好',
        keyName: 'value5',
        option: [{ //选择类型属性：数组枚举
          label: '游戏',
          value: 'game'
        }, {
          label: '旅行',
          value: 'travel'
        }],
        valid: false,
        value:['game']
      },
    ]
  },

  /* 图片上传 */
  afterRead(e) {
    const {
      file
    } = e.detail;
    // console.log(999,e);
    let index = null
    let keyName = e.currentTarget.dataset.params
    let item = this.data.configList.find((item, idx) => {
      index = idx
      return item.keyName == keyName
    })
    // console.log(123,item);
    item.value = []
    item.value.push({
      ...file,
      url: file.url
    })
    this.data.configList.splice(index, 1, item)

    this.setData({
      ['formData.' + `${keyName}`]: JSON.stringify(item.value),
      configList: this.data.configList
    })
  },
  fileDelete(e) {
    console.log(857, e);
    let deleteIndex = e.detail.index
    let index = null
    let keyName = e.currentTarget.dataset.params
    let item = this.data.configList.find((item, idx) => {
      index = idx
      return item.keyName == keyName
    })

    item.value.splice(deleteIndex, 1)
    this.data.configList.splice(index, 1, item)

    this.setData({
      ['formData.' + `${keyName}`]: JSON.stringify(item.value),
      configList: this.data.configList
    })
  },

  /* 前往签名 */
  goSignature(e) {
    wx.setStorageSync('signKey', e.currentTarget.dataset.params)
    wx.navigateTo({
      url: '/pages/signature/signature',
    })
  },

  /* 绑定刷新configList
    keyName:键，
    showValue:label展示值，
    ctx:上下文，
    formValue:label对应的value/也是后端对应属性的值
  */
  bindAndRefresh(keyName, showValue, ctx, formValue) {
    let index = null
    let item = ctx.data.configList.find((item, idx) => {
      index = idx
      return item.keyName == keyName
    })
    // console.log(123,item);
    item.value = showValue
    ctx.data.configList.splice(index, 1, item)
    ctx.setData({
      ['formData.' + `${keyName}`]: formValue ? formValue : showValue,
      configList: ctx.data.configList
    })
  },

  /* 获取地址 */
  /* 获取省市区级联 */
  bindRegionChange(e) {
    let index = null
    let keyName = e.currentTarget.dataset.params
    let item = this.data.configList.find((item, idx) => {
      index = idx
      return item.keyName == keyName
    })
    // console.log(123,item);
    item.value.cascader = e.detail.value
    this.data.configList.splice(index, 1, item)

    this.setData({
      ['formData.' + `${keyName}`]: JSON.stringify(item.value),
      configList: this.data.configList
    })
  },
  bindAddressInput(e) {
    // console.log(77777, e);
    let index = null
    let keyName = e.currentTarget.dataset.params
    let item = this.data.configList.find((item, idx) => {
      index = idx
      return item.keyName == keyName
    })
    // console.log(123,item);
    item.value.detail = e.detail.value
    this.data.configList.splice(index, 1, item)

    this.setData({
      ['formData.' + `${keyName}`]: item.value,
      configList: this.data.configList
    })
  },

  /* 获取定位 */
  getLocation(e) {
    let _self = this
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        //todo 借助后端返回对应的中文名/腾讯地图api
        let position = [res.longitude, res.latitude]
        _self.bindAndRefresh(e.currentTarget.dataset.params, JSON.stringify(position), _self)
      }
    })
  },
  /*  普通输入框，选择器绑定值 */
  bindKeyInput(e) {
    // 此处可传入data-temType 对e.detail.value的格式进行特殊设置
    // console.log(222, e.detail.value);
    this.setData({
      ['formData.' + `${e.currentTarget.dataset.params}`]: e.detail.value
    })
  },
  /* inspect点击监听与值绑定 */
  inspectItemInput(e) {
    let itemJsonObj = this.data.configList.find(item => item.keyName == e.currentTarget.dataset.parent)
    if (itemJsonObj && itemJsonObj.value && itemJsonObj.value.length > 0) {
      const {
        value
      } = itemJsonObj
      let index = value.findIndex(item => item.id == e.currentTarget.dataset.children)
      if (index != -1) {
        let checkde = e.currentTarget.dataset.check == "true"
        if (value[index].value == null) {
          value[index].value = checkde
        } else {
          if (checkde == value[index].value) {
            value[index].value = null
          } else {
            value[index].value = checkde
          }
        }

        this.setData({
          ['formData.' + `${e.currentTarget.dataset.parent}`]: JSON.stringify(value)
        })
        //要使得页面动态刷新，需要setData方法触发图层更新
        this.setData({
          configList: this.data.configList
        })
      }
    }
  },
  resetInspect(e) {
    let itemJsonObj = this.data.configList.find(item => item.keyName == e.currentTarget.dataset.parent)
    if (itemJsonObj && itemJsonObj.value && itemJsonObj.value.length > 0) {
      const {
        value
      } = itemJsonObj
      let index = value.findIndex(item => item.id == e.currentTarget.dataset.children)
      if (index != -1 && value[index].value != null) {
        value[index].value = null
        this.setData({
          ['formData.' + `${e.currentTarget.dataset.parent}`]: JSON.stringify(value)
        })
        //要使得页面动态刷新，需要setData方法触发图层更新
        this.setData({
          configList: this.data.configList
        })
      }
    }
  },
  /* table输入监听与值绑定 */
  tableItemInput(e) {
    let itemJsonObj = this.data.configList.find(item => item.keyName == e.currentTarget.dataset.parent)
    if (itemJsonObj && itemJsonObj.value && itemJsonObj.value.length > 0) {
      const {
        value
      } = itemJsonObj
      let index = value.findIndex(item => item.id == e.currentTarget.dataset.children)
      if (index != -1) {
        value[index].value = e.detail.value
        this.setData({
          ['formData.' + `${e.currentTarget.dataset.parent}`]: JSON.stringify(value)
        })
      }
    }
  },

  //提交form
  formSubmit() {
    util.validateForm(this.data.configList, this.data.formData, () => {
      //验证通过 提交逻辑
      console.log(111, this.data.formData);
      wx.showToast({
        title: '提交成功',
      })
    }, (e) => {
      wx.showToast({
        title: '' + e,
        icon: 'none'
      })
    })
  },
  //重置form
  formReset() {
    this.resetFormData()
    wx.showToast({
      title: '重置表单',
    })
  },
  resetFormData() {
    let newData = this.data.configList.map(item => {
      return item.keyName
    })
    let newObj = {}
    newData.forEach((item) => {
      newObj[item + ''] = null
    })
    this.setData({
      formData: newObj
    })
    // console.log('formData,', this.data.formData);
  },
  reBindFormData() {
    let formData = {}
    this.data.configList.forEach(item => {
      if (item.value) {
        //所有非string类型，转换为string
        formData[item.keyName] = (typeof item.value === 'string' ? item.value : JSON.stringify(item.value))
      }
    })
    console.log(663, formData);
    this.setData({
      formData: formData
    })
  },
  onLoad: function () {
    this.reBindFormData()
  },
  onShow: function () {
    // console.log(444,wx.getStorageSync('signature'));
    let signature = wx.getStorageSync('signature')
    let keyName = wx.getStorageSync('signKey')
    if (signature && keyName) {
      this.bindAndRefresh(keyName, signature, this)
      wx.removeStorage({
        key: 'signature',
      })
      wx.removeStorage({
        key: 'signKey',
      })
    }
  }
})